package nbcp.flux.feign

import com.fasterxml.jackson.databind.ObjectMapper
import nbcp.base.component.WebJsonMapper
import nbcp.base.enums.JsonSceneScopeEnum
import nbcp.base.extend.*
import nbcp.base.json.*
import nbcp.base.utils.SpringUtil
import org.springframework.http.HttpInputMessage
import org.springframework.http.MediaType
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type

class JsonHttpMessageConverter : MappingJackson2HttpMessageConverter() {
    override fun getObjectMapper(): ObjectMapper {
        return SpringUtil.getBean<WebJsonMapper>()
    }

    override fun getSupportedMediaTypes(): MutableList<MediaType> {
        return mutableListOf(MediaType.APPLICATION_JSON);
    }

    override fun read(type: Type, contextClass: Class<*>?, inputMessage: HttpInputMessage): Any? {

        if (type is ParameterizedType) {
            when (type.actualTypeArguments.size) {
                0 -> {}
                else -> {
                    var rawType = type.rawType
                    if (rawType is Class<*>) {
                        var paramTypes = type.actualTypeArguments.map { it as Class<*> }.toTypedArray();
                        var text = inputMessage.body.readContentString();
                        return text.FromGenericJson(rawType, *paramTypes, style = JsonSceneScopeEnum.WEB)
                    }
                }
            }
        }

        return super.read(type, contextClass, inputMessage)
    }
}